package com.wanpinghui.supplier.business;

import android.animation.ObjectAnimator;
import android.content.Intent;
import android.media.MediaPlayer;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.wanpinghui.supplier.R;
import com.wanpinghui.supplier.business.view.WVideoView;
import com.wanpinghui.supplier.business.view.PinchImageView;
import com.wanpinghui.supplier.common.BaseActivity;
import com.wanpinghui.supplier.widgets.TitlePanelLayoutUser;
import com.wanpinghui.wphlibrary.WPHSdk;
import com.wanpinghui.wphlibrary.common.RxEventType;
import com.wanpinghui.wphlibrary.common.toast.ToastManager;
import com.wanpinghui.wphlibrary.model.business.BusinessService;
import com.wanpinghui.wphlibrary.model.business.bean.CommentBean;
import com.wanpinghui.wphlibrary.model.business.bean.DynamicBean;
import com.wanpinghui.wphlibrary.model.business.bean.ThumbUpBean;
import com.wanpinghui.wphlibrary.model.oauth.OAuthService;
import com.yunshl.yunshllibrary.rxbus.RxBus;
import com.yunshl.yunshllibrary.rxbus.SubscriptionBean;
import com.yunshl.yunshllibrary.utils.TextUtil;

import org.xutils.common.util.DensityUtil;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.LinkedList;
import java.util.List;

import retrofit.callback.YRequestCallback;
import rx.functions.Action1;

/***
 * 功能描述:
 * 作者:qiujialiu
 * 时间:2018/1/29
 ***/
@ContentView(R.layout.layout_activity_dynamic_detail_image)
public class DynamicDetailImageActivity extends BaseActivity {
    private static final int REQUEST_COMMENT = 0x15;
    @ViewInject(R.id.tpl_title)
    private TitlePanelLayoutUser mLayoutTitle;
    @ViewInject(R.id.pager)
    private ViewPager pager;
    @ViewInject(R.id.tv_content)
    private TextView textViewContent;
    @ViewInject(R.id.ll_comment)
    private LinearLayout mLayoutComment;
    @ViewInject(R.id.ll_detail)
    private LinearLayout mLayoutDetail;
    @ViewInject(R.id.ll_like)
    private LinearLayout mLayoutLike;
    @ViewInject(R.id.ll_bottom)
    private LinearLayout mLayoutBottom;
    @ViewInject(R.id.root_view)
    private RelativeLayout mLayoutRoot;
    @ViewInject(R.id.tv_like_or_cancel)
    private TextView textViewLikeOrCancel;
    @ViewInject(R.id.tv_like_count)
    private TextView textViewLikeCount;

    final LinkedList<View> viewCache = new LinkedList<>();

    private DynamicBean mDynamicBean;
    private boolean isHide;
    private int type;
    @Override
    public String getName() {
        return null;
    }

    @Override
    public boolean isBar() {
        return false;
    }

    @Override
    public void initViews() {
        if (getIntent() != null) {
            String dataStr = getIntent().getStringExtra("data");
            if (TextUtil.isNotEmpty(dataStr)) {
                mDynamicBean = new Gson().fromJson(dataStr, new TypeToken<DynamicBean>(){}.getType());
            }
            if (mDynamicBean != null && mDynamicBean.getContentImgs() != null && mDynamicBean.getContentImgs().size() > 0) {
                type = mDynamicBean.getContentImgs().get(0).getType();
            }else {
                ToastManager.getInstance().showToast("加载出错了");
                finish();
            }
        }
    }

    @Override
    public void bindEvents() {
        mLayoutDetail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(DynamicDetailImageActivity.this, DynamicDetailActivity.class);
                intent.putExtra("data", new Gson().toJson(mDynamicBean));
                startActivity(intent);
            }
        });

        mLayoutComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(DynamicDetailImageActivity.this, CommentActivity.class);
                startActivityForResult(intent, REQUEST_COMMENT);
            }
        });

        mLayoutLike.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                likeDynamic(mDynamicBean.getId(), "赞".equals(textViewLikeOrCancel.getText().toString()));
            }
        });

        mLayoutTitle.setOnClickBacktrack(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


        RxBus.getInstance().toObserverable(SubscriptionBean.RxBusSendBean.class).subscribe(new Action1<SubscriptionBean.RxBusSendBean>() {
            @Override
            public void call(SubscriptionBean.RxBusSendBean rxBusSendBean) {
                if (rxBusSendBean.type == RxEventType.UPDATE_DYNAMIC) {
                    DynamicBean dynamicBean = (DynamicBean) rxBusSendBean.content;
                    mDynamicBean = dynamicBean;
                    if (mDynamicBean.haveILike(WPHSdk.getService(OAuthService.class).getUserId())) {
                        textViewLikeOrCancel.setText("取消");
                    }else {
                        textViewLikeOrCancel.setText("赞");
                    }
                }
            }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {

            }
        });

    }

    @Override
    public void initData() {
        if (TextUtil.isNotEmpty(mDynamicBean.getContent())) {
            textViewContent.setVisibility(View.VISIBLE);
            textViewContent.setText(mDynamicBean.getContent());
        }else {
            textViewContent.setVisibility(View.GONE);
        }
        if (mDynamicBean.haveILike(WPHSdk.getService(OAuthService.class).getUserId())) {
            textViewLikeOrCancel.setText("取消");
        }else {
            textViewLikeOrCancel.setText("赞");
        }
        if (mDynamicBean.getThumbUpCount() > 0) {
            textViewLikeCount.setVisibility(View.VISIBLE);
            textViewLikeCount.setText(Integer.toString(mDynamicBean.getThumbUpCount()));
        }else {
            textViewLikeCount.setVisibility(View.GONE);
        }
        pager.setAdapter(new PagerAdapter() {
            @Override
            public int getCount() {
                if (mDynamicBean == null) {
                    return 0;
                }else {
                    return mDynamicBean.getContentImgs() == null ? 0 : mDynamicBean.getContentImgs().size();
                }
            }

            @Override
            public boolean isViewFromObject(View view, Object o) {
                return view == o;
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                if (type == 1) {
                    PinchImageView piv;
                    if (viewCache.size() > 0) {
                        piv = (PinchImageView) viewCache.remove();
                        piv.reset();
                    } else {
                        piv = new PinchImageView(DynamicDetailImageActivity.this);
                    }
                    Glide.with(DynamicDetailImageActivity.this).load(mDynamicBean.getContentImgs().get(position).getUrl()).into(piv);
                    container.addView(piv);
                    piv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (!isHide) {
                                isHide = true;
                                ObjectAnimator.ofFloat(mLayoutTitle, "translationY", 0, -DensityUtil.dip2px(46)).setDuration(400).start();
                                ObjectAnimator.ofFloat(mLayoutBottom, "translationY", 0, DensityUtil.dip2px(47)).setDuration(400).start();
                            } else {
                                isHide = false;
                                ObjectAnimator.ofFloat(mLayoutTitle, "translationY", -DensityUtil.dip2px(46), 0).setDuration(400).start();
                                ObjectAnimator.ofFloat(mLayoutBottom, "translationY", DensityUtil.dip2px(47), 0).setDuration(400).start();
                            }
                        }
                    });
                    return piv;
                }else {
                    WVideoView videoView;
                    if (viewCache.size() > 0) {
                        videoView = (WVideoView) viewCache.remove();
                    } else {
                        videoView = new WVideoView(DynamicDetailImageActivity.this);
                    }
                    videoView.setVideoPath(mDynamicBean.getContentImgs().get(position).getUrl());
                    MediaController controller = new MediaController(DynamicDetailImageActivity.this);
                    videoView.setMediaController(controller);
                    controller.setVisibility(View.GONE);
                    videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mp) {
                            mp.start();
                            mp.setLooping(true);
                        }
                    });
                    videoView.start();
                    videoView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (!isHide) {
                                isHide = true;
                                ObjectAnimator.ofFloat(mLayoutTitle, "translationY", 0, -DensityUtil.dip2px(46)).setDuration(400).start();
                                ObjectAnimator.ofFloat(mLayoutBottom, "translationY", 0, DensityUtil.dip2px(47)).setDuration(400).start();
                            } else {
                                isHide = false;
                                ObjectAnimator.ofFloat(mLayoutTitle, "translationY", -DensityUtil.dip2px(46), 0).setDuration(400).start();
                                ObjectAnimator.ofFloat(mLayoutBottom, "translationY", DensityUtil.dip2px(47), 0).setDuration(400).start();
                            }
                        }
                    });
                    container.addView(videoView);
                    return videoView;
                }
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                if (type == 1) {
                    PinchImageView piv = (PinchImageView) object;
                    container.removeView(piv);
                    viewCache.add(piv);
                }else {
                    WVideoView piv = (WVideoView) object;
                    container.removeView(piv);
                    viewCache.add(piv);
                }
            }

            @Override
            public void setPrimaryItem(ViewGroup container, int position, Object object) {
//                if (type == 1) {
//                    PinchImageView piv = (PinchImageView) object;
//                    Glide.with(DynamicDetailImageActivity.this).load(mDynamicBean.getContentImgs().get(position).getUrl()).into(piv);
//                }else {
//                    final WVideoView videoView = (WVideoView) object;
//                    videoView.post(new Runnable() {
//                        @Override
//                        public void run() {
//                            videoView.start();
//                        }
//                    });
//                }
            }
        });

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_COMMENT && resultCode == RESULT_OK) {
            String result = data.getStringExtra("result");
            if (TextUtil.isNotEmpty(result)) {
                commentDynamic(mDynamicBean.getId(), 0, result);
            }
        }
    }

    private void commentDynamic(int dynamic,int userId, String content) {
        WPHSdk.getService(BusinessService.class).commentDynamic(dynamic, userId, content, new YRequestCallback<List<CommentBean>>() {
            @Override
            public void onSuccess(List<CommentBean> var1) {
                mDynamicBean.setReplyList(var1);
                RxBus.getInstance().send(SubscriptionBean.createSendBean(RxEventType.UPDATE_DYNAMIC,mDynamicBean));
            }

            @Override
            public void onFailed(int var1, String message) {
                ToastManager.getInstance().showToast(message);
            }

            @Override
            public void onException(Throwable var1) {
                var1.printStackTrace();
            }
        });
    }

    private void likeDynamic(int dynamicId, boolean like) {
        WPHSdk.getService(BusinessService.class).addOrCancelLike(dynamicId, like, new YRequestCallback<List<ThumbUpBean>>() {
            @Override
            public void onSuccess(List<ThumbUpBean> var1) {
                mDynamicBean.setLikeList(var1);
                RxBus.getInstance().send(SubscriptionBean.createSendBean(RxEventType.UPDATE_DYNAMIC,mDynamicBean));
                if (mDynamicBean.getThumbUpCount() > 0) {
                    textViewLikeCount.setVisibility(View.VISIBLE);
                    textViewLikeCount.setText(Integer.toString(mDynamicBean.getThumbUpCount()));
                }else {
                    textViewLikeCount.setVisibility(View.GONE);
                }
            }

            @Override
            public void onFailed(int var1, String message) {

            }

            @Override
            public void onException(Throwable var1) {
                var1.printStackTrace();
            }
        });
    }
}
